package com.mlr.mlrcturebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mlr.mlrcturebackend.model.entity.PictureTag;
import com.mlr.mlrcturebackend.model.entity.Tag;
import com.mlr.mlrcturebackend.service.PictureTagService;
import com.mlr.mlrcturebackend.mapper.PictureTagMapper;
import com.mlr.mlrcturebackend.service.TagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author mlr
 * @description 针对表【picture_tag(图片标签关联表)】的数据库操作Service实现
 */
@Service
public class PictureTagServiceImpl extends ServiceImpl<PictureTagMapper, PictureTag>
        implements PictureTagService {

    @Resource
    private TagService tagService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTagsToPicture(Long pictureId, List<Long> tagIds) {
        if (pictureId == null || tagIds == null || tagIds.isEmpty()) {
            return;
        }

        List<PictureTag> pictureTagList = new ArrayList<>();
        Date now = new Date();

        for (Long tagId : tagIds) {
            PictureTag pictureTag = new PictureTag();
            pictureTag.setPictureId(pictureId);
            pictureTag.setTagId(tagId);
            pictureTag.setCreateTime(now);
            pictureTag.setUpdateTime(now);
            pictureTag.setIsDelete(0);
            pictureTagList.add(pictureTag);
        }
        this.saveBatch(pictureTagList);
    }

    @Override
    public List<Tag> getTagsByPictureId(Long pictureId) {
        if (pictureId == null) {
            return new ArrayList<>();
        }

        List<Long> tagIds = this.baseMapper.selectTagIdsByPictureId(pictureId);
        if (tagIds.isEmpty()) {
            return new ArrayList<>();
        }

        return tagService.listByIds(tagIds);
    }

    @Override
    public List<Long> getPictureIdsByTagId(Long tagId) {
        if (tagId == null) {
            return new ArrayList<>();
        }

        return this.baseMapper.selectPictureIdsByTagId(tagId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePictureTags(Long pictureId, List<Long> tagIds) {
        if (pictureId == null) {
            return;
        }

        // 删除原有的关联
        this.remove(new QueryWrapper<PictureTag>().eq("pictureId", pictureId));

        // 添加新的关联
        if (tagIds != null && !tagIds.isEmpty()) {
            this.addTagsToPicture(pictureId, tagIds);
        }
    }

    @Override
    public void batchAddPictureTags(List<PictureTag> pictureTagList) {
        if (pictureTagList == null || pictureTagList.isEmpty()) {
            return;
        }
        this.baseMapper.batchInsert(pictureTagList);
    }
}